<template>
    <div class="app-container">
        <el-card>
            <el-page-header @back="goBack">
                <template #content>
                    <div
                        class="flex items-center"
                        style="display: flex; justify-content: space-between"
                    >
                        <div style="display: flex; align-items: center">
                            <div>
                                {{
                                    route.query.readonly
                                        ? '查看生产纸张下单标准设置'
                                        : route.query.id
                                        ? '生产纸张下单标准设置'
                                        : '新增生产纸张下单标准设置'
                                }}
                            </div>
                            <el-tag
                                v-if="route.query.status"
                                :type="tagType"
                                style="margin-left: 10px"
                            >
                                {{ route.query.code }}
                            </el-tag>
                        </div>
                    </div>
                </template>
                <template #extra>
                    <div>
                        <el-button
                            v-if="!route.query.readonly"
                            class="button"
                            type="primary"
                            @click="handleSubmit"
                        >
                            保 存
                        </el-button>
                    </div>
                </template>
            </el-page-header>
        </el-card>
        <el-card style="margin-top: 10px">
            <el-collapse v-model="activeNames">
                <el-collapse-item disabled title="基本信息" name="1">
                    <template #title>
                        <el-icon style="color: #4479f6">
                            <Position />
                        </el-icon>
                        <span class="title">基本信息</span>
                    </template>
                    <div>
                        <el-form
                            :model="form"
                            :rules="rules"
                            :disabled="Boolean(route.query.readonly)"
                            ref="paperProductionRef"
                            label-width="100px"
                        >
                            <el-row :gutter="20">
                                <el-col :span="8">
                                    <el-form-item label="印刷方式" prop="printType">
                                        <el-select
                                            v-model="form.printType"
                                            class="m-2"
                                            placeholder="请选择印刷方式"
                                            style="width: 100%"
                                        >
                                            <el-option
                                                v-for="item in mes_paper_package"
                                                :key="item.label"
                                                :label="item.label"
                                                :value="item.value"
                                            />
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8" v-if="form.printType == 2">
                                    <el-form-item label="版材尺寸" prop="sheetSize">
                                        <el-select
                                            style="width: 100%"
                                            v-model="form.sheetSize"
                                            class="m-2"
                                            placeholder="请选择版材尺寸"
                                        >
                                            <el-option
                                                v-for="item in ems_machine_info_size"
                                                :key="item.value"
                                                :label="item.label"
                                                :value="item.value"
                                            />
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8" v-if="form.printType == 1">
                                    <el-form-item label="印色" prop="printColour">
                                        <el-select
                                            style="width: 100%"
                                            v-model="form.printColour"
                                            class="m-2"
                                            multiple
                                            collapse-tags-tooltip
                                            placeholder="请选择印色"
                                        >
                                            <el-option
                                                v-for="item in ems_order_print_color"
                                                :key="item.value"
                                                :label="item.label"
                                                :value="item.value"
                                            />
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8" v-if="form.printType == 2">
                                    <el-form-item label="车间" prop="workshopId">
                                        <el-select
                                            @change="changeWorkShopName"
                                            style="width: 100%"
                                            v-model="form.workshopId"
                                            placeholder="请选择"
                                        >
                                            <el-option
                                                v-for="item in ems_workshop"
                                                :key="item.value"
                                                :label="item.label"
                                                :value="item.value"
                                            />
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                            </el-row>

                            <el-row :gutter="20">
                                <el-col :span="24">
                                    <el-form-item label="备注">
                                        <el-input
                                            v-model="form.remark"
                                            type="textarea"
                                            placeholder="请输入内容"
                                        ></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>
                    </div>
                </el-collapse-item>
            </el-collapse>
        </el-card>
        <el-card style="margin-top: 10px">
            <el-collapse v-model="activeNames">
                <el-collapse-item disabled title="设置明细" name="1">
                    <template #title>
                        <el-icon style="color: #4479f6">
                            <Position />
                        </el-icon>
                        <span class="title">设置明细</span>
                    </template>
                    <el-button
                        style="margin-bottom: 5px"
                        type="primary"
                        size="small"
                        plain
                        icon="Plus"
                        @click="handleAdddetails"
                        :disabled="Boolean(route.query.readonly)"
                    >
                        新增
                    </el-button>
                    <span v-if="route.query.readonly">  
                       <span v-if="form.printType==1"> (Ps: 版材尺寸1055*811、1030*790 、930*721 损耗系数固定为0.03 )</span>
                    </span>
                    <!-- <el-button style="margin-bottom: 5px;" type="primary" size="small" plain icon="Upload"
                        @click="handleImport" :disabled="Boolean(route.query.readonly)">导入</el-button>
                    <el-button style="margin-bottom: 5px;" type="primary" size="small" plain icon="Download"
                        @click="handleExport" :disabled="Boolean(route.query.readonly)">导出</el-button> -->
                    <el-table :data="paperOrderDetails" border style="width: 100%">
                        <el-table-column
                            type="index"
                            label="序号"
                            width="80"
                            align="center"
                        ></el-table-column>
                        <el-table-column prop="printCount" label="下单数量" align="center">
                            <template #default="scope">
                                <el-input
                                    :disabled="Boolean(route.query.readonly)"
                                    v-model="scope.row.printCount"
                                ></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column prop="lossCoefficient" label="损耗系数(%)" align="center">
                            <template #default="scope">
                                <el-input
                                    v-model="scope.row.lossCoefficient"
                                    :disabled="Boolean(route.query.readonly)"
                                    type="number"
                                ></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column
                            fixed="right"
                            label="操作"
                            width="200"
                            v-if="!route.query.readonly"
                            min-width="120"
                            align="center"
                        >
                            <template #default="scope">
                                <!-- <el-button link type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button> -->
                                <el-button
                                    link
                                    type="primary"
                                    size="small"
                                    @click="handledetailsDel(scope.row)"
                                >
                                    删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-collapse-item>
            </el-collapse>
        </el-card>

        <!-- 用户导入对话框 -->
        <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
            <el-upload
                ref="uploadRef"
                :limit="1"
                accept=".xlsx, .xls"
                :headers="upload.headers"
                :action="upload.url + '?updateSupport=' + upload.updateSupport"
                :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress"
                :on-success="handleFileSuccess"
                :auto-upload="false"
                drag
            >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                    将文件拖到此处，或
                    <em>点击上传</em>
                </div>
                <template #tip>
                    <div class="el-upload__tip text-center">
                        <div class="el-upload__tip">
                            <el-checkbox v-model="upload.updateSupport" />
                            是否更新已经存在的用户数据
                        </div>
                        <span>仅允许导入xls、xlsx格式文件。</span>
                        <el-link
                            type="primary"
                            :underline="false"
                            style="font-size: 12px; vertical-align: baseline"
                            @click="importTemplate"
                        >
                            下载模板
                        </el-link>
                    </div>
                </template>
            </el-upload>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitFileForm">确 定</el-button>
                    <el-button @click="upload.open = false">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
import useTagsViewStore from '@/store/modules/tagsView'
import useUserStore from '@/store/modules/user'
const tagsViewStore = useTagsViewStore()
import machineDialog from '@/components/SearchWorkBenchS'
const { proxy } = getCurrentInstance()

const { ems_workshop, mes_paper_package, ems_machine_info_size, ems_order_print_color } =
    proxy.useDict(
        'ems_workshop',
        'mes_paper_package',
        'ems_machine_info_size',
        'ems_order_print_color'
    )
import { paperOrderAdd, paperOrderGetById } from '@/api/basicInfo/PaperProduction.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import { downLoadBlob, downLoad } from '@/utils/ruoyi'
const router = useRouter()
const route = useRoute()
const activeNames = ['1']
const one = ref(false)
const two = ref(false)
const three = ref(false)
const visibleMachine = ref(false)
const paperProductionRef = ref(null)
const mesPlaceorderMachineinfoList = ref([]) //相关机台
const paperOrderDetails = ref([]) //设置明细
const msg = ref('')
import { getToken } from '@/utils/auth'
/*** 用户导入参数 */
const upload = reactive({
    // 是否显示弹出层（用户导入）
    open: false,
    // 弹出层标题（用户导入）
    title: '',
    // 是否禁用上传
    isUploading: false,
    // 是否更新已经存在的用户数据
    updateSupport: 0,
    // 设置上传的请求头部
    headers: { Authorization: 'Bearer ' + getToken() },
    // 上传的地址
    url: import.meta.env.VITE_APP_BASE_API + 'mes/info/importData',
})
const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
    },
    rules: {
        printType: [{ required: true, message: '印刷方式不能为空', trigger: 'change' }],
        sheetSize: [{ required: true, message: '版材尺寸不能为空', trigger: 'change' }],
        workshopId: [{ required: true, message: '车间不能为空', trigger: 'change' }],
        printColour: [{ required: true, message: '印色不能为空', trigger: 'change' }],
    },
})

const { queryParams, form, rules } = toRefs(data)
const userInfo = useUserStore()
const tagType = computed(() => {
    return route.query.status == 0 ? '' : 'danger'
})
//车间
const changeWorkShopName = row => {
    ems_workshop.value.forEach(item => {
        if (row == item.value) {
            form.value.workshopName = item.label
        }
    })
}

if (route.query.id) {
    paperOrderDetails.value = []
    paperOrderGetById(route.query.id).then(response => {
        const data = response.data || {}
        form.value = { ...data }
        if (data.printColour) {
            form.value.printColour = data.printColour.split(',')
        }
        paperOrderDetails.value = response.data.paperOrderDetails
    })
} else {
    form.value = {}
    form.value.createBy = userInfo.name
}
const handleEdit = row => {
    row.isDisabled = true
}
const handledetailsDel = row => {
    const index = paperOrderDetails.value.indexOf(row)
    if (index !== -1) {
        paperOrderDetails.value.splice(index, 1)
    }
}
const handleSubmit = () => {
    paperProductionRef.value.validate(valid => {
        if (valid) {
            const formData = form.value
            let printColour = undefined
            if (formData.printColour && formData.printColour.length > 0) {
                printColour = formData.printColour.join(',')
            }
            if (formData.id)  {
               paperOrderDetails.value.forEach(item=>{
                    item.paperOrderId = formData.id
                })
            } 
            console.log(paperOrderDetails.value);
            formData.paperOrderDetails = paperOrderDetails.value
            paperOrderAdd({ ...formData, printColour }).then(response => {
                if (response.code === 200) {
                    if (formData.id) {
                        ElMessage({
                            message: '编辑成功',
                            type: 'success',
                        })
                    } else {
                        ElMessage({
                            message: '新增成功',
                            type: 'success',
                        })
                    }
                    goBack()
                }
            })
        }
    })
}

//选择机台
const selectorTable = () => {
    visibleMachine.value = true
}
const handleDel = row => {
    const index = mesPlaceorderMachineinfoList.value.indexOf(row)
    if (index !== -1) {
        mesPlaceorderMachineinfoList.value.splice(index, 1)
    }
}
//明细
const handleAdddetails = () => {
    paperOrderDetails.value.push({ isDisabled: true })
}
//  返回
const goBack = () => {
    tagsViewStore.delView(route)
    router.go(-1)
}

/** 导入按钮操作 */
function handleImport() {
    if (!form.value.machinetype) {
        return ElMessage({
            message: '请先选择机器类型',
            type: 'warning',
        })
    }
    upload.title = '生产纸张下单标准设置导入'
    upload.open = true
}
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
    upload.isUploading = true
}
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
    upload.open = false
    upload.isUploading = false
    proxy.$refs['uploadRef'].handleRemove(file)

    if (response.code == 200) {
        msg.value = '导入成功'
    } else {
        msg.value = '导入失败'
    }

    proxy.$alert(msg.value)

    paperOrderDetails.value.push(...response.rows)
}
const handleExport = () => {
    const jsonArray = JSON.stringify(paperOrderDetails.value)
    exportszmx({ type: form.value.machinetype, data: jsonArray }).then(response => {
        downLoad(response.msg, '生产纸张下载标准导出')
    })
}
/** 提交上传文件 */
function submitFileForm() {
    proxy.$refs['uploadRef'].submit()
}
/** 下载模板操作 */
function importTemplate() {
    console.log('form.value.machinetype', form.value.machinetype)
    if (!form.value.machinetype) {
        return ElMessage({
            message: '请先选择机器类型',
            type: 'warning',
        })
    }
    setTemplate({ type: form.value.machinetype }).then(res => {
        console.log('res', res)
        downLoadBlob(res, '生产纸张下单标准设置模版')
    })
}
</script>

<style lang="scss" scoped></style>
